//
//  WeatherQueryViewController.m
//  SinceLe
//
//  Created by lanou3g on 15/11/18.
//  Copyright © 2015年 李元喜. All rights reserved.
//

#import "WeatherQueryViewController.h"
#import "WeatherViewController.h"
#import "WeatherModel.h"
#import <RESideMenu.h>

@interface WeatherQueryViewController ()

@property (weak, nonatomic) IBOutlet UITextField *weatherQueryText;

@property (weak, nonatomic) IBOutlet UIButton *queryButton;

@property (nonatomic, strong) NSString* cityID;

@property (nonatomic, strong) NSString* cityName;

@property (nonatomic, strong)WeatherModel* model;

- (IBAction)queryButtonClicked:(UIButton *)sender;


@end

@implementation WeatherQueryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"天气查询";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Left"
                                                                             style:UIBarButtonItemStylePlain
                                                                            target:self
                                                                            action:@selector(presentLeftMenuViewController:)];
    _queryButton.layer.masksToBounds = YES;
    _queryButton.layer.cornerRadius = 10;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark ---- 获取要查询城市的ID
-(void)request1: (NSString*)httpUrl withHttpArg1: (NSString*)HttpArg  {
    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, HttpArg];
    NSURL *url = [NSURL URLWithString: urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"GET"];
    [request addValue: @"adc9015f0385768f9e79479723788539" forHTTPHeaderField: @"apikey"];
    [NSURLConnection sendAsynchronousRequest: request
                                       queue: [NSOperationQueue mainQueue]
                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
                               if (error) {
                                   NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
                               } else {
                                   NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                                   NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   NSLog(@"HttpResponseCode:%ld", responseCode);
                                   NSLog(@"HttpResponseBody %@",responseString);
                                   NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                                   NSDictionary* dicc = dic[@"retData"];
                                   _cityID = dicc[@"cityCode"];
                                   NSString *httpUrl = @"http://apis.baidu.com/apistore/weatherservice/recentweathers";
                                   NSString *httpArg = [NSString stringWithFormat:@"cityname=%@&cityid=%@", _cityName, _cityID ];
                                   [self request: httpUrl withHttpArg: httpArg];

                               }
                           }];
}


#pragma mark ---- 获取天气信息
-(void)request: (NSString*)httpUrl withHttpArg: (NSString*)HttpArg  {
    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", httpUrl, HttpArg];
    NSURL *url = [NSURL URLWithString: urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"GET"];
    [request addValue: @"adc9015f0385768f9e79479723788539" forHTTPHeaderField: @"apikey"];
    [NSURLConnection sendAsynchronousRequest: request
                                       queue: [NSOperationQueue mainQueue]
                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
                               if (error) {
                                   NSLog(@"Httperror: %@%ld", error.localizedDescription, (long)error.code);
                               } else {
                                   NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                                   NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   NSLog(@"HttpResponseCode:%ld", (long)responseCode);
                                   NSLog(@"HttpResponseBody %@",responseString);
                                   NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                                   NSDictionary* dicc = dic[@"retData"];
                                   [self setWeatherModel:dicc];
                               }
                           }];
}


#pragma mark ---- 设置model
-(void)setWeatherModel:(NSDictionary *)dic{
    //记住一定要初始化model
    _model = [[WeatherModel alloc] init];
    _model.city = dic[@"city"];
    NSDictionary* dict = dic[@"today"];
    _model.date = dict[@"date"];
    _model.week = dict[@"week"];
    _model.curTemp = dict[@"curTemp"];
    _model.fengli = dict[@"fengli"];
    _model.hightemp = dict[@"hightemp"];
    _model.lowtemp = dict[@"lowtemp"];
    _model.type = dict[@"type"];
    
    NSArray* arr = dict[@"index"];
    for (int i = 0; i< arr.count; i ++) {
        if (i == 0) {
            NSDictionary* d0 = arr[0];
            _model.tempLabel = d0[@"details"];
        }else if (i == 1){
            NSDictionary* d1 = arr[1];
            _model.ziwaixianLabel = d1[@"details"];
        }else if (i == 2){
            NSDictionary* d2 = arr[2];
            _model.wearLabel = d2[@"details"];
        }else if(i == 5){
            NSDictionary* d3 = arr[5];
            _model.sunClothlabel = d3[@"details"];
        }
    }
    
    WeatherViewController* weather = [[WeatherViewController alloc] init];
    weather.model = _model;
    [self.navigationController pushViewController:weather animated:YES];

}

- (IBAction)queryButtonClicked:(UIButton *)sender {
    //解析数据(获取城市ID)
    NSString *httpUrl1 = @"http://apis.baidu.com/apistore/weatherservice/cityinfo";
    NSString* cityStr = _weatherQueryText.text;
     NSString * encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( kCFAllocatorDefault, (CFStringRef)cityStr, NULL, NULL,  kCFStringEncodingUTF8 ));
    _cityID = cityStr;
    NSString *httpArg1 = [NSString stringWithFormat:@"cityname=%@", encodedString];
    [self request1: httpUrl1 withHttpArg1: httpArg1];

}
@end
